/* eslint-disable no-mixed-spaces-and-tabs */
import axiosOrigin from 'axios';
import Logger from '../base/logger';
import { IvcsError } from '../base/error';
import { ivcsErrorCodeEnum } from '../base/const';
import https from 'https';
import http from 'http';
const axios = axiosOrigin.create({
	httpsAgent: new https.Agent({
		rejectUnauthorized: false,
		keepAlive: true,
	}),
	httpAgent: new http.Agent({
		keepAlive: true,
	}),
});
import { isEmptyString, isJsonString, logObject } from './tool';

let isRefreshing = false;
let waitRequestList = [];
let userId = undefined;
let ticket = undefined;
let accessToken = undefined;
axios.interceptors.response.use(
	function (resp) {
		//判断登录接口缓存ticket和token
		if (resp.config.url.indexOf('ivcs/api/v1/auth/logon') != -1) {
			accessToken = resp.data && resp.data.data && resp.data.data.accessToken ? resp.data.data.accessToken : '';
			let tokenData = resp.data && resp.data.data && resp.data.data.tokenData ? resp.data.data.tokenData : null;
			userId = tokenData ? tokenData.data.id : undefined;
			ticket = resp.data && resp.data.data && resp.data.data.ticket ? resp.data.data.ticket : '';
		}
		return resp;
	},
	function (error) {
		if (error.response && error.response.status === 401 && error.response.data && error.response.data.code === '1101') {
			let body = {
				userId: userId,
				ticket: ticket,
			};
			const { config } = error.response;
			if (!isRefreshing) {
				isRefreshing = true;
				//TODO bugfix get request url
				return refreshToken(body)
					.then(resp => {
						console.log('refresh token success', resp);
						accessToken = resp.data.accessToken;
						error.response.config.headers['x-access-token'] = accessToken;
						waitRequestList.forEach(cb => cb(accessToken));
						waitRequestList = [];
						return axios.request(error.response.config);
					})
					.catch(e => {
						console.log('refersh ticket error', e, e.response);
						return Promise.reject(e);
					})
					.finally(() => {
						isRefreshing = false;
					});
			} else {
				return new Promise(resolve => {
					waitRequestList.push(token => {
						config.headers['x-access-token'] = token;
						resolve(axios.request(config));
					});
				});
			}
		} else {
			return Promise.reject(error);
		}
	}
);

/**
 * 登录
 * @param {string} url 登录url
 * @param {object} para body参数
 * @returns Promise.<object, Error>
 */
export const login = (url, para) => {
	return axios.post(url + '/ivcs/api/v1/auth/logon', para, {
		headers: {
			'Content-Type': 'application/json',
		},
	});
};

/**
 * 游客免密登录
 * @param {string} url 登录url
 * @param {object} para body参数
 * @returns Promise.<object, Error>
 */
export const visitorLogin = (url, para) => {
	const crypto = require('crypto');
	const Accept = '*/*';
	const ContentType = 'application/json; charset=UTF-8';
	const time = new Date().toISOString();
	// const signatureHeaders = '';
	const stringToSign = 'POST' + '-' + Accept + '-' + ContentType.toLocaleUpperCase() + '-' + time + '-';
	console.log('stringToSign', stringToSign);
	const xCaSignature = crypto.createHash('sha224').update(stringToSign).digest('hex');
	console.log('xCaSignature', xCaSignature);
	return axios.post(url + '/ivcs/api/v1/auth/visitor', para, {
		headers: {
			accept: Accept,
			'content-type': ContentType,
			time: time,
			// 'x-ca-signature-headers': signatureHeaders,
			'x-ca-signature': xCaSignature,
		},
	});
};

/**
 * 根据openId注册访客
 * @param {string} url 登录url
 * @param {object} para body参数
 * @returns Promise.<object, Error>
 */
export const registerWithOpenId = (url, para) => {
	return axios.post(url + '/ivcs/api/v1/auth/register/openid', para, {
		headers: {
			'Content-Type': 'application/json',
		},
	});
};

/**
 * token失效，重新刷新链接
 * @param {string} url 访问url
 * @param {object} para body参数
 * @returns Promise.<object, Error>
 */
export const refreshToken = (url, para) => {
	return axios.post(url + '/ivcs/api/v1/auth/refresh-token', para, {
		headers: {
			'Content-Type': 'application/json',
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 上传日志文件
 * @param {string} url
 * @param {string} sessionId
 * @param {object} para
 */
export const uploadlogs = (url, sessionId, para) => {
	return axios.post(url + '/ivcs/clc/session/' + sessionId, para, {
		headers: {
			'Content-Type': 'text/plain',
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 创建一个有时长的token，用来鉴权推拉流在rtmp server
 * @param {string} url 请求的url
 * @param {string} token 登录之后返回的用户信息token
 * @param {number} validityTime 有效时长，默认是30分钟
 * @returns Promise.<object, Error>
 */
export const createRtmpServerTokenWithValidityTime = (url, token, validityTime) => {
	return axios.post(
		url + '/ivcs/api/v1/oneTimeToken',
		{
			validityTime: validityTime,
		},
		{
			headers: {
				'x-access-token': token,
				'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
			},
		}
	);
};

/**
 * 小程序把rtmp流推送到zms
 * @param {string} backendUrl 后台url
 * @param {string} roomId 房间id
 * @param {string} owner joinroom后返回的selfId
 * @param {string} url rtmp流的url
 * @param {object} attributes 推到zms后的forward流的属性,可自定义 如{type:'customer'}
 * @returns Promise.<object, Error>
 */
export const streamingIns = (backendUrl, roomId, owner, url, attributes = {}) => {
	let para = {
		url: url,
		media: {
			audio: 'auto',
			video: true,
		},
		transport: {
			protocol: 'tcp',
			bufferSize: 4096,
		},
		owner: owner,
		attributes: attributes,
	};
	let requestUrl = backendUrl + '/ivcs/api/v1/rooms/' + roomId + '/streaming-ins';
	return axios.post(requestUrl, para, {
		headers: {
			'content-type': 'application/json',
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 根据userid获取绑定的分组
 * @param {string} url 访问的url
 * @param {string} token 鉴权的token
 * @param {string} userId
 * @param {number} page
 * @param {number} pagesize
 * @returns Promise.<object, Error>
 */
export const getGroupsWithUserId = (url, token, userId, page = 1, pagesize = 1000) => {
	return axios.get(url + '/ivcs/api/v1/user-group-relations' + '?page=' + page + '&pageSize=' + pagesize + '&userId=' + userId, {
		headers: {
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 获取所有的分组
 * @param {string} url 访问的url
 * @param {string} token 鉴权的token
 * @returns Promise.<object, Error>
 */
export const getGroups = (url, token) => {
	return axios.get(url + '/ivcs/api/v1/user/groups', {
		headers: {
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 把流加入到mix流中
 * @param {string} url 访问的url
 * @param {string} roomId 房间id
 * @param {string} streamId 流id
 * @param {string} token 鉴权的token
 * @returns Promise.<object, Error>
 */
export const addStreamToMix = (url, roomId, streamId, token) => {
	return axios.post(
		url + '/ivcs/api/v1/rooms/' + roomId + '/streams/' + streamId + '/patch',
		[
			{
				op: 'add',
				path: '/info/inViews',
				value: 'common',
			},
		],
		{
			headers: {
				'Content-Type': 'application/json',
				'x-access-token': token,
				'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
			},
		}
	);
};

/**
 * 开启asr功能
 * @param {*} url
 * @param {*} roomId
 * @param {*} streamId
 * @param {*} owner
 * @param {*} type
 * @param {*} token
 */
export const startAsr = (url, roomId, streamId, owner, type = 'baidu', token) => {
	return axios.post(
		url + '/ivcs/api/v1/rooms/' + roomId + '/asr',
		{
			owner: owner,
			stream_id: streamId,
			type: type,
		},
		{
			headers: {
				'Content-Type': 'application/json',
				'x-access-token': token,
				'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
			},
		}
	);
};

/**
 * 停止asr识别
 * @param {*} url
 * @param {*} roomId
 * @param {*} asrId
 * @param {*} token
 */
export const deleteAsr = (url, roomId, asrId, token) => {
	return axios.delete(url + '/ivcs/api/v1/rooms/' + roomId + '/asr/' + asrId, {
		headers: {
			'Content-Type': 'application/json',
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 获取当前rtmp server上的所有的rtmp流
 * @param {string} url 后台url
 * @param {string} token accesstoken
 */
export const getStat = (url, token) => {
	let requestUrl = url + '/ivcs/api/v1/private/rtmp/stat';
	return axios.get(requestUrl, {
		headers: {
			'Content-Type': 'application/json',
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 开始录制,录制成mp4格式
 * @param {string} backendUrl 访问的url
 * @param {string} roomId 房间id
 * @param {string} audioStreamId 音频来源流id
 * @param {string} videoStreamId  视频来源流id
 * @param {string} token
 * @param {string} sessionId
 * @param {string} type type: "system", "agent-screen", "regional-screen", 系统录像、坐席录屏、区域录屏
 * @returns Promise.<object, Error>
 */
export const startRecord = (backendUrl, roomId, audioStreamId, videoStreamId, token, sessionId, type = 'agent-screen') => {
	let url = backendUrl + '/ivcs/api/v1/private/rooms/' + roomId + '/recordings';
	let audio = audioStreamId
		? {
				from: audioStreamId,
				format: {
					codec: 'aac',
					sampleRate: 48000,
					channelNum: 2,
				},
		  }
		: false;
	let video = videoStreamId
		? {
				from: videoStreamId,
				format: {
					codec: 'h264',
					profile: 'CB',
				},
		  }
		: false;
	let para = {
		container: 'auto',
		media: {
			audio: audio,
			video: video,
		},
		sessionId: sessionId,
		type: type,
	};
	return axios.post(url, para, {
		headers: {
			'Content-Type': 'application/json',
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 停止录制
 * @param {string} url 访问的url
 * @param {string} roomId 房间id
 * @param {string} recordId 录制id
 * @param {string} token 鉴权token
 * @param {string} sessionId 会话id
 * @returns Promise.<object, Error>
 */
export const stopRecord = (url, roomId, recordId, token, sessionId) => {
	return axios.delete(url + '/ivcs/api/v1/private/rooms/' + roomId + '/sessions/' + sessionId + '/recordings/' + recordId, {
		headers: {
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 根据分组名 获取详情信息
 * @param {string} url 访问的url
 * @param {string} name 分组名字
 * @param {string} token 鉴权token
 * @returns Promise.<object, Error>
 */
export const getGroupsDetailWithName = (url, name, token) => {
	return axios.get(url + '/ivcs/api/v1/groups/names/' + name, {
		headers: {
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 根据分组id 获取详情信息
 * @param {string} url 访问的url
 * @param {string} id 分组id
 * @param {string} token 鉴权token
 * @returns Promise.<object, Error>
 */
export const getGroupsDetailWithId = (url, id, token) => {
	return axios.get(url + '/ivcs/api/v1/groups/' + id, {
		headers: {
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 上传文件
 * @param {string} url 服务的地址
 * @param {FormData} data formData
 * @param {string} token 登录后返回的token
 * @returns Promise.<object, Error>
 */
export const uploadFileWithFormData = (url, data, token) => {
	return axios.post(url + '/ivcs/api/v1/upload', data, {
		headers: {
			'Content-Type': 'multipart/form-data',
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 录像中途异常上报
 * @param {string} url 服务的地址
 * @param {FormData} data formData
 * @param {string} token 登录后返回的token
 * @returns Promise.<object, Error>
 */
export const updateRecordStatus = (url, recordId, token) => {
	return axios.post(
		url + '/ivcs/api/v1/private/recording/' + recordId + '/halfWayFail',
		{},
		{
			headers: {
				'x-access-token': token,
				'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
			},
		}
	);
};

/**
 * 把流推送到外流媒体服务，如rtmp
 * @param {string} url 服务的地址
 * @param {string} roomId 房间id
 * @param {object} para body参数
 * @returns Promise.<object, Error>
 */
export const streamOuts = (url, roomId, para) => {
	let requestUrl = url + '/ivcs/api/v1/rooms/' + roomId + '/streaming-outs';
	return axios.post(requestUrl, para, {
		headers: {
			'Content-Type': 'application/json',
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 添加base64图片到mix流
 * @param {string} url  服务的地址
 * @param {string} roomId roomId
 * @param {string} para 请求参数
 */
export const addPictureToMixStream = (url, roomId, para) => {
	let stream = roomId + '-common';
	let requestUrl = url + '/ivcs/api/v1/rooms/' + roomId + '/streams/' + stream + '/pictures';
	return axios.post(requestUrl, para, {
		headers: {
			'Content-Type': 'application/json',
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 删除base64图片在mix流中
 * @param {string} url 服务的地址
 * @param {string} roomId  roomId
 * @param {string} pictureId 添加成功后返回的id.. all = 删除所有图片
 */
export const removePictureInMixStream = (url, roomId, pictureId = 'all') => {
	let stream = roomId + '-common';
	let requestUrl = url + '/ivcs/api/v1/rooms/' + roomId + '/streams/' + stream + '/pictures/' + pictureId;
	return axios.delete(requestUrl, {
		headers: {
			'Content-Type': 'application/json',
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 停止流推
 * @param {string} url 服务的地址
 * @param {string} roomId 房间id
 * @param {string} streamingOutsId streaming-outs返回的记录id
 * @param {string} token 鉴权token
 * @returns Promise.<object, Error>
 */
export const stopStreamingOuts = (url, roomId, streamingOutsId, token) => {
	let requestUrl = url + '/ivcs/api/v1/rooms/' + roomId + '/streaming-outs/' + streamingOutsId;
	return axios.delete(requestUrl, {
		headers: {
			'x-access-token': token,
			'x-session-id': process.env.ivcsAgentMode != 1 ? window.ivcsSessionId : global && global.ivcsSessionId ? global.ivcsSessionId : null,
		},
	});
};

/**
 * 获取分组下的表单模版根据分组名
 * @deprecated since version 1.0.5
 * @param {string} url 访问url
 * @param {string} name 分组名
 * @param {string} token 鉴权token
 * @param {string} needThrownException 是否需要留痕异常
 * @returns Promise.<object, Error>
 */
export async function getFormTemplatesWithGroupsName(url, name, token, needThrownException = false) {
	return await new Promise((resolve, reject) => {
		let requestUrl = url + '/ivcs/api/v1/groups/names/' + name;
		getGroupsDetailWithName(url, name, token)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				if (resp.data.formTemplates) {
					resolve(resp.data.formTemplates);
				} else {
					if (needThrownException) {
						let response = new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, logWithRequestResponse(requestUrl, resp, null, false));
						reject(response);
					} else {
						resolve([]);
					}
				}
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				if (needThrownException) {
					let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
					reject(response);
				} else {
					resolve([]);
				}
			});
	});
}

/**
 * 根据分组id获取表单模版
 * @deprecated since version 1.0.5
 * @param {string} url 访问url
 * @param {string} groupId 分组id
 * @param {string} token 鉴权token
 * @param {boolean} needThrownException 是否需要留痕异常
 * @returns Promise.<object, Error>
 */
export async function getFormTemplatesWithGroupsId(url, groupId, token, needThrownException = false) {
	return await new Promise((resolve, reject) => {
		let requestUrl = url + '/ivcs/api/v1/groups/' + groupId;
		getGroupsDetailWithId(url, groupId, token)
			.then(resp => {
				Logger.info(`ivcs-js-sdk:get groups detail with ${groupId} success,${JSON.stringify(resp)},${new Date()}`);
				//Logger.info(`get groups detail with ${name} success,${JSON.stringify(resp)},${new Date()}`);
				logWithRequestResponse(requestUrl, resp, null, true);
				if (resp.data.formTemplates) {
					resolve(resp.data.formTemplates);
				} else {
					if (needThrownException) {
						let response = new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, logWithRequestResponse(requestUrl, resp, null, false));
						reject(response);
					} else {
						resolve([]);
					}
				}
			})
			.catch(error => {
				Logger.info(`ivcs-js-sdk:get groups detail with ${groupId},${error},${JSON.stringify(error.response)},${new Date()}`);
				//Logger.info(`get groups detail with ${name},${error},${JSON.stringify(error.response)},${new Date()}`);
				logWithRequestResponse(requestUrl, null, error, true);
				if (needThrownException) {
					let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
					reject(response);
				} else {
					resolve([]);
				}
			});
	});
}

/**
 * 将某一个流加入到mix流中
 * @param {string} backendUrl 访问url
 * @param {string} roomId 房间id
 * @param {string} streamId 流id
 * @param {string} accessToken 鉴权token
 * @param {boolean} needThrownException 是否需要留痕异常
 */
export async function addStreamToMixStream(backendUrl, roomId, streamId, accessToken, needThrownException = false) {
	return await new Promise((resolve, reject) => {
		let requestUrl = backendUrl + '/ivcs/api/v1/rooms/' + roomId + '/streams/' + streamId;
		addStreamToMix(backendUrl, roomId, streamId, accessToken)
			.then(resp => {
				// Logger.info(`add stream to mix success,${streamId},${JSON.stringify(resp)},${new Date()}`);
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve();
			})
			.catch(error => {
				//Logger.info(`add stream to mix failed,${streamId},${error},${JSON.stringify(error.response)},${new Date()}`);
				logWithRequestResponse(requestUrl, null, error, true);
				if (needThrownException) {
					let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
					reject(response);
				} else {
					resolve();
				}
			});
	});
}

/**
 * 开启asr识别
 * @param {string} backendUrl 访问url
 * @param {string} roomId 房间id
 * @param {string} streamId 流id
 * @param {string} accessToken 鉴权token
 * @param {boolean} needThrownException 是否需要留痕异常
 */
export async function startAsrEvent(backendUrl, roomId, streamId, accessToken, owner, type, needThrownException = false) {
	return await new Promise((resolve, reject) => {
		resolve('ok');
		// let requestUrl = backendUrl + '/ivcs/api/v1/rooms/' + roomId + '/asr/';
		// startAsr(backendUrl, roomId, streamId,owner,type, accessToken)
		// 	.then(resp => {
		// 		// Logger.info(`add stream to mix success,${streamId},${JSON.stringify(resp)},${new Date()}`);
		// 		logWithRequestResponse(requestUrl, resp, null, true);
		// 		resolve();
		// 	})
		// 	.catch(error => {
		// 		//Logger.info(`add stream to mix failed,${streamId},${error},${JSON.stringify(error.response)},${new Date()}`);
		// 		logWithRequestResponse(requestUrl, null, error, true);
		// 		if (needThrownException) {
		// 			let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
		// 			reject(response);
		// 		} else {
		// 			resolve();
		// 		}
		// 	});
	});
}
/**
 * 小程序把rtmp流推送到zms
 * @param {string} backendUrl 后台url
 * @param {string} roomId 房间id
 * @param {string} owner joinroom后返回的selfId
 * @param {string} url rtmp流的url
 * @param {object} attributes 推到zms后的forward流的属性,可自定义 如{type:'customer'}
 * @param {boolean} needThrownException 是否需要留痕异常
 * @returns Promise.<string, Error> 流id
 */
export async function pushRtmpUrlToZms(backendUrl, roomId, owner, url, attributes, needThrownException = false) {
	return await new Promise((resolve, reject) => {
		let requestUrl = backendUrl + '/ivcs/api/v1/rooms/' + roomId + '/streaming-ins';
		streamingIns(backendUrl, roomId, owner, url, attributes)
			.then(resp => {
				if (resp && resp.data && resp.data.id) {
					resolve(resp.data.id);
				} else {
					if (needThrownException) {
						let response = new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, logWithRequestResponse(requestUrl, resp, null, false));
						reject(response);
					} else {
						resolve(null);
					}
				}
			})
			.catch(error => {
				if (needThrownException) {
					let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
					reject(response);
				} else {
					resolve(null);
				}
			});
	});
}

/**
 * 录制流
 * @param {string} backendUrl 访问url
 * @param {string} roomId 房间id
 * @param {string} audioStreamId 声音来源流id
 * @param {string} videoStreamId 视频来源流id
 * @param {string} accessToken 鉴权token
 * @param {boolean} needThrownException 是否需要留痕异常
 * @param {string} sessionId sessionId
 * @param {string} type type: "system", "agent-screen", "regional-screen", 系统录像、坐席录屏、区域录屏
 * @returns Promise.<object, Error>
 */
export async function recordStream(backendUrl, roomId, audioStreamId, videoStreamId, accessToken, needThrownException = false, sessionId, type = 'agent-screen') {
	return await new Promise((resolve, reject) => {
		let requestUrl = backendUrl + '/ivcs/api/v1/rooms/' + roomId + '/recordings';
		startRecord(backendUrl, roomId, audioStreamId, videoStreamId, accessToken, sessionId, type)
			.then(resp => {
				//Logger.info(`record mix stream to success,${JSON.stringify(resp)},${new Date()}`);
				logWithRequestResponse(requestUrl, resp, null, true);
				if (resp.data && resp.data.recordingId) {
					resolve(resp.data.recordingId);
				} else {
					if (needThrownException) {
						let response = new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, logWithRequestResponse(requestUrl, resp, null, false));
						reject(response);
					} else {
						resolve(null);
					}
				}
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				// Logger.info(`record stream failed,audioStreamId:${audioStreamId},videoStreamId:${videoStreamId},${error},${JSON.stringify(error.response)},${new Date()}`);
				if (needThrownException) {
					let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
					reject(response);
				} else {
					resolve(null);
				}
			});
	});
}

/**
 * 判断一个rtmp url 是否推流成功
 * @param {string} backendUrl 后台地址
 * @param {string} accessToken accesstoken
 * @param {string} rtmpUrlPath live-pusher推流的地址路径 如rtmp://161.189.61.223/liveshow/12345678  则rtmpUrlPath为12345678
 * @returns Promise.<boolean, Error>
 */
export async function getRtmpStat(backendUrl, accessToken, rtmpUrlPath) {
	return await new Promise((resolve, reject) => {
		let requestUrl = backendUrl + '/ivcs/api/v1/private/rtmp/stat';
		getStat(backendUrl, accessToken)
			.then(resp => {
				Logger.info('ivcs-js-sdk:getrtmpstat', rtmpUrlPath, resp.data);
				logWithRequestResponse(requestUrl, resp, null, true);
				if (resp.data && resp.data.includes(rtmpUrlPath)) {
					resolve(true);
				} else {
					reject(false);
				}
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				reject(false);
			});
	});
}

/**
 * 停止录制
 * @param {string} backendUrl 访问的url
 * @param {string} roomId 房间id
 * @param {string} recordId 录制id
 * @param {string} accessToken 鉴权token
 * @param {boolean} needThrownException 是否需要留痕异常
 * @param {string} sessionId 会话id
 * @returns Promise.<object, Error>
 */
export async function stopRecordStream(backendUrl, roomId, recordId, accessToken, needThrownException = false, sessionId) {
	return await new Promise((resolve, reject) => {
		let requestUrl = backendUrl + '/ivcs/api/v1/rooms/' + roomId + '/recordings/' + recordId;
		stopRecord(backendUrl, roomId, recordId, accessToken, sessionId)
			.then(resp => {
				// Logger.info(`stop record stream to success,${JSON.stringify(resp)},${new Date()}`);
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				//Logger.info(`stop record stream failed,${recordId},${error},${JSON.stringify(error.response)},${new Date()}`);
				logWithRequestResponse(requestUrl, null, error, true);
				if (needThrownException) {
					let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
					reject(response);
				} else {
					resolve(null);
				}
			});
	});
}

/**
 * 上传文件
 * @param {string} url 服务的地址
 * @param {FormData} data formData
 * @param {string} token 登录后返回的token
 * @returns Promise.<object, Error>
 */
export async function uploadFile(url, formData, token) {
	return await new Promise((resolve, reject) => {
		let requestUrl = url + '/ivcs/api/v1/upload';
		uploadFileWithFormData(url, formData, token)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				if (resp.data && resp.data.code == 200) {
					var response = resp.data.data;
					resolve(response);
				} else {
					let response = new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, logWithRequestResponse(requestUrl, resp, null, false));
					reject(response);
				}
			})
			.catch(error => {
				//Logger.info(`upload file failed,url:${url},formdata:${formData},${error},${JSON.stringify(error.response)},${new Date()}`);
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 把流推送到其他流媒体服务
 * @param {string} url 访问的url
 * @param {string} roomId 房间id
 * @param {string} audioId 声音来源流id
 * @param {string} videoId 视频来源流id
 * @param {string} streamOutUrl 往外推的url。如rtmp://xxx.xx.xx.xx/liveshow
 * @returns Promise.<object, Error>
 */
export async function streamOutsToMediaServer(url, roomId, audioId, videoId, streamOutUrl) {
	return await new Promise((resolve, reject) => {
		let audio = audioId
			? {
					from: audioId,
			  }
			: false;
		let video = videoId
			? {
					from: videoId,
			  }
			: false;
		let para = {
			media: {
				audio: audio,
				video: video,
			},
			url: streamOutUrl,
		};
		let requestUrl = url + '/ivcs/api/v1/rooms/' + roomId + '/streaming-outs';
		streamOuts(url, roomId, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				if (resp.data) {
					resolve(resp);
				} else {
					let response = new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, logWithRequestResponse(requestUrl, resp, null, false));
					reject(response);
				}
			})
			.catch(error => {
				//Logger.info(`streamOuts failed,url:${url},streamOutUrl:${streamOutUrl},${error},${JSON.stringify(error.response)},audioId,${audioId},videoId,${videoId}${new Date()}`);
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 小程序订阅机器人的流
 * @param {string} url 访问的后台url
 * @param {string} roomId 房间id
 * @param {string} owner 加入房间后的participantId
 * @param {string} robotRtmpUrl 坐席的流rtmp地址
 */
export async function subscribeRobotStream(url, roomId, owner, robotRtmpUrl) {
	return await new Promise((resolve, reject) => {
		let para = {
			media: {
				audio: {
					from: roomId + '-common',
				},
				video: {
					from: roomId + '-common',
				},
			},
			url: robotRtmpUrl,
			owner: owner,
			protocol: 'rtmp',
		};
		let requestUrl = url + '/ivcs/api/v1/rooms/' + roomId + '/streaming-outs';
		streamOuts(url, roomId, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				if (resp.data) {
					resolve(resp);
				} else {
					let response = new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, logWithRequestResponse(requestUrl, resp, null, false));
					reject(response);
				}
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 创建一个有时长的token，用来鉴权推拉流在rtmp server
 * @param {string} url 请求的url
 * @param {string} token 登录之后返回的用户信息token
 * @param {number} validityTime 有效时长，默认是30分钟
 * @returns Promise.<object, Error>
 */
export async function createTokenWithRtmpServer(url, token, validityTime) {
	return await new Promise((resolve, reject) => {
		let requestUrl = url + '/ivcs/api/v1/oneTimeToken';
		createRtmpServerTokenWithValidityTime(url, token, validityTime)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				if (resp.data && resp.data.token) {
					resolve(resp.data.token);
				} else {
					let response = new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, logWithRequestResponse(requestUrl, resp, null, false));
					reject(response);
				}
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 坐席登录
 * @param {string} backendUrl 访问的url
 * @param {string} name 姓名
 * @param {string} pwd 密码
 * @param {string} org 机构
 * @param {string} compressedPublicKey 密码加密公钥
 * @returns Promise.<object, Error>
 */
export async function agentLogin(backendUrl, name, pwd, org, compressedPublicKey) {
	return await new Promise((resolve, reject) => {
		let password = pwd;
		if (compressedPublicKey) {
			const sm2 = require('sm-crypto').sm2;
			const cipherMode = 1; // 1 - C1C3C2，0 - C1C2C3，默认为1
			let encryptData = sm2.doEncrypt(pwd, compressedPublicKey, cipherMode); // 加密结果
			password = encryptData;
		}
		let para = {
			userName: name,
			pwd: password,
			role: 'agent',
			org: org,
		};
		Logger.info('ivcs-js-sdk:request body', para);
		let requestUrl = backendUrl + '/ivcs/api/v1/auth/logon';
		login(backendUrl, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				Logger.info(`ivcs-js-sdk:agent login failed,${error.response},at,${new Date()}`);
				var response;
				if (error.response) {
					response = responseError(error.response);
				} else {
					Logger.info('ivcs-js-sdk:agent login error', error);
					response = new IvcsError(responseErrorCode(error.response || error), JSON.stringify(error.message));
				}
				logWithRequestResponse(requestUrl, null, error, true);
				reject(response);
			});
	});
}

/**
 * 刷新新的token
 * @param {string} backendUrl 访问的url
 * @param {string} userId 用户id
 * @param {string} ticket 登录后返回的ticket
 * @returns Promise.<object, Error>
 */
export async function refreshNewToken(backendUrl, userId, ticket) {
	return await new Promise((resolve, reject) => {
		let para = {
			userId: userId,
			ticket: ticket,
		};
		Logger.info('ivcs-js-sdk:request body', para);
		let requestUrl = backendUrl + '/ivcs/api/v1/auth/refresh-token';
		refreshToken(backendUrl, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp.data);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 获取坐席的所有分组
 * @param {string} backendUrl 访问url
 * @param {string} token 鉴权token
 * @returns Promise.<object, Error>
 */
export async function getAgentGroups(backendUrl, token) {
	return await new Promise((resolve, reject) => {
		let requestUrl = backendUrl + '/ivcs/api/v1/user/groups';
		getGroups(backendUrl, token)
			.then(resp => {
				var groupsList = [];
				if (resp.data && resp.data.length > 0) {
					resp.data.forEach(item => {
						groupsList.push(item.group);
					});
				}
				resolve(groupsList);
				logWithRequestResponse(requestUrl, resp, null, true);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				var response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 访客登录
 * @param {string} backendUrl 访客url
 * @param {string} name 姓名
 * @param {string} pwd 密码
 * @param {string} org 机构
 * @returns Promise.<object, Error>
 */
export async function customerLogin(backendUrl, name, pwd, org) {
	return await new Promise((resolve, reject) => {
		let para = {
			userName: name,
			pwd: pwd,
			role: 'customer',
			org: org,
		};
		Logger.info('ivcs-js-sdk:request body', para);
		let requestUrl = backendUrl + '/ivcs/api/v1/auth/logon';
		login(backendUrl, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 访客免密登录
 * @param {string} backendUrl 访问url
 * @param {string} userId 访客id
 * @param {string} org 机构
 * @returns Promise.<object, Error>
 */
export async function visitorFreeLogin(backendUrl, userId, org) {
	return await new Promise((resolve, reject) => {
		let para = {
			id: userId,
			org: org,
		};
		Logger.info('ivcs-js-sdk:request body', para);
		let requestUrl = backendUrl + '/ivcs/api/v1/auth/visitor';
		visitorLogin(backendUrl, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				const result = error.response;
				// 1303 Invalid Signature
				// 1301 参数错误
				// 404 不存在该机构
				let errorCode = result?.data?.code || '400';
				if (result?.data?.code == 1301) {
					if (result?.data?.data?.errorCode == 4) {
						errorCode = '404';
					}
				}
				let errorMessage = result?.data?.message;
				let response = new IvcsError(errorCode, logWithRequestResponse(requestUrl, null, errorMessage, false));
				reject(response);
			});
	});
}

/**
 * 访客根据openId登录
 * @param {string} backendUrl 请求的后台服务地址
 * @param {string} openId openId
 * @param {string} org org
 * @returns Promise.<object, Error>
 */
export async function customerLoginWithOpenId(backendUrl, openId, org) {
	return await new Promise((resolve, reject) => {
		let para = {
			openId: openId,
			org: org,
		};
		Logger.info('ivcs-js-sdk:request body', para);
		let requestUrl = backendUrl + '/ivcs/api/v1/auth/register/openid';
		registerWithOpenId(backendUrl, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 外系统坐席登录
 * @param {string} backendUrl 访问的url
 * @param {string} name 姓名
 * @param {string} pwd 密码
 * @param {string} org 机构
 * @param {string} type 外系统标识
 * @returns Promise.<object, Error>
 */
export async function externalAgentLogin(backendUrl, name, pwd, org, type) {
	return await new Promise((resolve, reject) => {
		let para = {
			userName: name,
			pwd: pwd,
			role: 'agent',
			org: org,
		};
		if (type == 'chinaums') {
			para.loginUms = true;
		}
		Logger.info('ivcs-js-sdk:request body', para);
		let requestUrl = backendUrl + '/ivcs/api/v1/auth/logon';
		login(backendUrl, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 坐席加密登录
 * @param {string} backendUrl 访问的url
 * @param {string} name 姓名
 * @param {string} pwd 密码
 * @param {string} org 机构
 * @param {string} encrypt 加密方式 MD5 SHA1 RSA AES DES 等
 * @returns Promise.<object, Error>
 */
export async function agentLoginWithEncrypt(backendUrl, name, pwd, org, encrypt, compressedPublicKey) {
	return await new Promise((resolve, reject) => {
		let password = pwd;
		if (compressedPublicKey) {
			const sm2 = require('sm-crypto').sm2;
			const cipherMode = 1; // 1 - C1C3C2，0 - C1C2C3，默认为1
			let encryptData = sm2.doEncrypt(pwd, compressedPublicKey, cipherMode); // 加密结果
			password = encryptData;
		}
		let para = {
			userName: name,
			pwd: password,
			role: 'agent',
			org: org,
			encrypt: encrypt,
		};
		Logger.info('ivcs-js-sdk:request body', para);
		let requestUrl = backendUrl + '/ivcs/api/v1/auth/logon';
		login(backendUrl, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				Logger.info(`ivcs-js-sdk:request login failed,${error.response || error},at,${new Date().toISOString()}`);
				let response = new IvcsError(responseErrorCode(error.response || error), error.response || error);
				logWithRequestResponse(requestUrl, null, error, true);
				reject(response);
			});
	});
}

/**
 * 坐席登录根据票据id
 * @param {string} backendUrl
 * @param {string} ticketId
 */
export async function agentLoginWithTicketId(backendUrl, ticketId) {
	return await new Promise((resolve, reject) => {
		let para = {
			ticketId: ticketId,
		};
		Logger.info('ivcs-js-sdk:request body', para);
		let requestUrl = backendUrl + '/ivcs/api/v1/auth/logon';
		login(backendUrl, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}
/**
 * 获取当前机构所有分组
 * @param {string} backendUrl 访问url
 * @param {string} token 鉴权token
 * @returns Promise.<object, Error>
 */
export const getAllGroups = (backendUrl, token) => {
	return axios.get(backendUrl + '/ivcs/api/v1/groups/select/options', {
		headers: {
			'x-access-token': token,
		},
	});
};
/**
 * 根据response设置错误信息
 * @param {object} response api请求的返回值
 * @returns {IvcsError}
 */
export function responseError(response) {
	if (response && response.data) {
		let code = response.data.code ? response.data.code : ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED;
		let message = response.data.message ? response.data.message : response.data;
		return new IvcsError(code, message);
	} else {
		return new IvcsError(ivcsErrorCodeEnum.ERROR_REQUEST_API_FAILED, response);
	}
}

/**
 * api请求失败，设置返回的错误码
 * @param {object} response axios-request-callbackData
 * @returns {string} '401':'账号失效','1302':'新旧密码不一致','1001':'账号不存在'
 */
export function responseErrorCode(response) {
	if (response && response.status === 401) {
		return '401';
	}
	if (response && response.data && response.data.code) {
		return response.data.code;
	}
	//network error
	return '500';
}

/**
 * 打印每个网络请求的返回日志
 * @param {string} requestUrl 请求的url
 * @param {object} response   返回值
 * @param {object} error 错误返回
 * @param {boolean} needLog 是否需要打印
 * @returns {string} 日志
 */
export function logWithRequestResponse(requestUrl, response, error, needLog) {
	let message = `time:${new Date()},requestUrl:${requestUrl} `;
	try {
		if (response) {
			message = message + `response status:${response.status} `;
			if (response.data && response.data.code) {
				message = message + `code:${response.data.code} `;
			}
			if (isJsonString(response)) {
				message = message + `data:${JSON.stringify(response)}`;
			} else if (response.data && isJsonString(response.data)) {
				message = message + `data:${JSON.stringify(response.data)}`;
			} else if (response.data && response.data.data && isJsonString(response.data.data)) {
				message = message + `data:${JSON.stringify(response.data.data)}`;
			} else if (response.data && response.data.data) {
				let data = response.data.data;
				message = message + `data:` + logObject(data) + ' ';
			} else if (response.data && !response.data.data) {
				let data = response.data;
				message = message + `data:` + logObject(data) + ' ';
			} else if (!isEmptyString(response)) {
				message = message + `data:${response}`;
			}
		}
		if (error) {
			if (isJsonString(error)) {
				message = message + `error:${JSON.stringify(error)}`;
			} else {
				message = message + `error:${error}`;
			}
			message = message + `error:${error}`;
		}
		needLog && Logger.debug(message);
		return message;
	} catch (error) {
		Logger.info('ivcs-js-sdk:log error', error, new Date().toISOString());
	}
}

/**
 * 坐席工号/用户名添加到mix混流中
 * @param { string } backendUrl 访问 url
 * @param { object } params 请求参数
 * @returns Promise.<object, Error>
 */
export const recordStreamByAgentName = (backendUrl, params) => {
	return axios.post(
		backendUrl + `/ivcs/api/v1/sessions/${params.sessionId}/streams/${params.streamId}/agentName`,
		{ agentName: params.agentName },
		{
			headers: {
				'x-access-token': params.token,
			},
		}
	);
};

/**
 * 设置开画时间，是否有画面 会话质量
 * @param {*} backendUrl 
 * @param {*} data {
  "sessionId": "123042565742905730",
  "subscribeId": "ahkhkhvddd",
  "fromClientId": "632361349702263600",
  "fromClientName": "person-agent",
  "fromClientRole": "agent",
  "toClientId": "172383322895894430",
  "toClientName": "c",
  "toClientRole": "customer",
  "hasFrame": false,
  "openingTime": 1000,
  "isVideo":true
}
 * @param {*} sessionId 
 * @param {*} accessToken 
 * @returns 
 */
export const setSessionStreamQuality = (backendUrl, data, sessionId, accessToken) => {
	return axios.post(backendUrl + `/ivcs/api/v1/sessionStreamQuality`, data, {
		headers: {
			'x-access-token': accessToken,
			'x-session-id': sessionId,
		},
	});
};

/**
 * 设置订阅的卡顿，平均延时
 * @param {*} backendUrl 
 * @param {*} data 
 * {
  "sessionId": "892611756860548700",
  "averageSoundDelay": 10,
  "averageFrameDelay": 10,
  "screenStuckRatio": 14
}
 * @param {*} subscribeId 
 * @param {*} sessionId 
 * @param {*} accessToken 
 * @returns 
 */
export const setSesssionCallQuality = (backendUrl, data, subscribeId, sessionId, accessToken) => {
	return axios.post(backendUrl + `/ivcs/api/v1/sessionStreamQuality/${subscribeId}`, data, {
		headers: {
			'x-access-token': accessToken,
			'x-session-id': sessionId,
		},
	});
};

/**
 *  坐席工号/用户名添加到mix混流中，即添加到录像文件中
 * @param {string} backendUrl 访问 url
 * @param {string} sessionId 会话 ID
 * @param {string} streamId 录制流 ID
 * @param {string} agentName 坐席工号/用户名
 * @param {string} token token
 * @returns Promise.<object, Error>
 */
export async function addAgentNameInRecordFile(backendUrl, sessionId, streamId, agentName, token) {
	return await new Promise((resolve, reject) => {
		let params = {
			sessionId,
			streamId,
			agentName,
			token,
		};
		Logger.info('ivcs-js-sdk:request body', params);
		let requestUrl = backendUrl + `/ivcs/api/v1/sessions/${params.sessionId}/streams/${params.streamId}/agentName`;
		recordStreamByAgentName(backendUrl, params)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * base64图片添加到混流中
 * @param {string} backendurl 服务端访问url
 * @param {string} roomId roomId
 * @param {string} para  请求参数
 * @returns Promise.<object, Error>
 */
export async function addBase64ImgToMixStream(backendurl, roomId, para) {
	return await new Promise((resolve, reject) => {
		Logger.info('ivcs-js-sdk:addBase64ImgToMixStream request body', para);
		let stream = roomId + '-common';
		let requestUrl = backendurl + '/ivcs/api/v1/rooms/' + roomId + '/streams/' + stream + '/pictures';
		addPictureToMixStream(backendurl, roomId, para)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp.data);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}

/**
 * 混流中移除base64图片
 * @param {string} backendurl 服务端访问url
 * @param {string} roomId  roomId
 * @param {string} pictureId 添加成功后返回的id.. all = 删除所有图片
 * @returns Promise.<object, Error>
 */
export async function removeBase64ImgInMixStream(backendurl, roomId, pictureId) {
	return await new Promise((resolve, reject) => {
		let stream = roomId + '-common';
		let requestUrl = backendurl + '/ivcs/api/v1/rooms/' + roomId + '/streams/' + stream + '/pictures/' + pictureId;
		removePictureInMixStream(backendurl, roomId, pictureId)
			.then(resp => {
				logWithRequestResponse(requestUrl, resp, null, true);
				resolve(resp.data);
			})
			.catch(error => {
				logWithRequestResponse(requestUrl, null, error, true);
				let response = new IvcsError(responseErrorCode(error.response || error), logWithRequestResponse(requestUrl, null, error, false));
				reject(response);
			});
	});
}
